package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.DIshDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * setmeal和SetmealDish的controller
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套菜
     * 1.将套餐的基本属性插入套餐表
     * 2.将套餐包含的菜品插入套餐菜品关系表
     * @param setmealDto
     * @return
     */
    @PostMapping
    //删除套餐时，就清空套餐的所有数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        //将套餐的基本信息插入套餐表，因为setmealDto继承了setmeal，所以可以直接调用save方法，传入setmealDto对象
        boolean save = setmealService.save(setmealDto);
        //获取套餐的id（再执行完套餐的插入以后生成了id，dto里面的setmealId就有值了）
        Long setmealId = setmealDto.getId();
        //此时的菜品中是缺少套餐id的，遍历菜品，给setmealId赋值
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes=setmealDishes.stream().map((item)->{
//            //创建一个setmealDish对象
//            SetmealDish setmealDish = new SetmealDish();
//            //将setmeal对象拷贝到setmealDish对象中
//            BeanUtils.copyProperties(item,setmealDish);
//            //设置setmealDish中setmealId的值
//            setmealDish.setSetmealId(item.getId());
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());//将所有的item对象都收集起来，从新赋值给setmealDishes

        boolean b = setmealDishService.saveBatch(setmealDishes);
        if (save&&b){
            return R.success("添加套餐成功");
        }else{
            return R.error("添加套餐失败");
        }
    }

    /**
     * 分页条件查询查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Transactional//开启事务管理
    @GetMapping("/page")
    public R<Page> selectByPage(int page,int pageSize,String name){
        Page<Setmeal> setmealPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //设置排序构造器
        queryWrapper.orderByAsc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, queryWrapper);
        List<Setmeal> records = setmealPage.getRecords();
        Page<SetmealDto> setmealDtoPage=new Page<>(page,pageSize);
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        List<SetmealDto> list;
        list=records.stream().map((item)->{
            Long categoryId = item.getCategoryId();
            LambdaQueryWrapper<Category> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(Category::getId,categoryId);
            Category category = categoryService.getOne(queryWrapper1);
            //创建一个setmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //将setmeal拷贝到setmealDto对象上
            BeanUtils.copyProperties(item,setmealDto);
            //给setmealDto对象设置套餐名
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);

        if (setmealDtoPage!=null){
            return R.success(setmealDtoPage);
        }else {
            return R.error("分页查询失败");
        }
    }


    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @GetMapping("/list")
    public R<List<SetmealDto>> getByCategoryId(Setmeal setmeal){
        Long id = setmeal.getCategoryId();
        Integer status = setmeal.getStatus();
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(Setmeal::getCategoryId,id).eq(Setmeal::getStatus,status);
        List<Setmeal> setmealList = setmealService.list(queryWrapper);


        List<SetmealDto> setmealDtoList;
        setmealDtoList=setmealList.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);

            //获取每个菜品的id，查询对应的菜品口味
            Long id1 = item.getId();
            LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper();
            lqw.eq(SetmealDish::getSetmealId,id);
            List<SetmealDish> list1 = setmealDishService.list(lqw);
            setmealDto.setSetmealDishes(list1);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtoList);

    }

}
